<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" align-center>
    <el-form ref="equipUsageFormRef" :model="tableItem" :rules="rules" label-position="right">
      <div style="padding: 10px 0;margin-left: 140px;">请选择结算账期里的一个日期</div>
      <el-form-item label="结算日期" label-width="140px" prop="settleDate">
        <el-date-picker v-model="tableItem.settleDate" type="date" clearable format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" placeholder="请选择一个结算日期" style="width: 200px" />
      </el-form-item>

      <el-form-item label="当前用量" label-width="140px" prop="currentUsage">
        <el-input-number v-model="tableItem.currentUsage" :precision="2" :step="0.01" :min="0" style="width: 200px"
          placeholder="请输入当前用量" controls-position="right" />
        <span style="margin-left: 5px;">{{ tableItem.usageUnit }}</span>
      </el-form-item>

      <el-form-item label="上期用量" label-width="140px" prop="previousUsage">
        <el-input-number v-model="tableItem.previousUsage" :precision="2" :step="0.01" :min="0" style="width: 200px"
          placeholder="请输入上期用量" controls-position="right" />
        <span style="margin-left: 5px;">{{ tableItem.usageUnit }}</span>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateData">保 存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { editEquipUsage } from '@/api/settle'
import { validate } from '@/utils/validate'

const tableItem = reactive({
  id: null,
  settleDate: '',
  currentUsage: null,
  previousUsage: null,
  enterpriseId: null,
  usageUnit: ''
})

const rules = reactive({
  currentUsage: [{ required: true, message: '请输入当前用量', trigger: 'blur' }],
  settleDate: [{ required: true, message: '请选择结算日期', trigger: 'blur' }],
})

const dialogVisible = ref(false)
const dialogTitle = ref('编辑设备用量信息')

const reset = () => {
  tableItem.id = null
  tableItem.settleDate = ''
  tableItem.currentUsage = null
  tableItem.previousUsage = null
  tableItem.enterpriseId = null
  tableItem.usageUnit = ''
}

const equipUsageFormRef = ref(null)

const emit = defineEmits(['listChange'])

const updateData = async () => {
  const valid = await validate(equipUsageFormRef)
  if (valid) {
    const params = JSON.parse(JSON.stringify(tableItem))
    editEquipUsage(params)
      .then(() => {
        emit('listChange')
        reset()
        dialogVisible.value = false
        ElMessage.success('更新成功！')
      })
      .catch(() => {
        reset()
        dialogVisible.value = false
        ElMessage.error('更新失败！')
      })
  }
}

defineExpose({ dialogVisible, tableItem, dialogTitle })

</script>
<style lang="scss" scoped></style>
